package com.example.mybatisplus.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplus.Entity.UserEntity;
import com.example.mybatisplus.Mapper.UserMapper;
import com.example.mybatisplus.Pojo.Result;
import com.example.mybatisplus.Pojo.ResultCode;
import com.example.mybatisplus.Service.UserService;
import com.example.mybatisplus.model.SearchModel;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource(name = "userMapper")//@Resource与@AutoWired一致。但可以指定name属性来指定beanName
    // 但如果name对应的bean不存在，则会抛出异常，且没有required(setter属性注入）属性
    private UserMapper userMapper;








    @Override
    public UserEntity findByEmail(@Param("email") String email) {
        return userMapper.findByEmail(email);
    }

    @Override
    public List<UserEntity> findAll() {//非分页查询，直接获取所有的用户信息
        return userMapper.findAll();
    }

    @Override //分页查询，根据当前页 和 页大小获取每页的用户信息
    public IPage<UserEntity> selectAll(SearchModel<UserEntity> search) {
        Page<UserEntity> page = new Page<>(search.getPageNum(), search.getPageSize());
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();

        if (search.getData() != null && search.getData().getName() != null) {
            wrapper.like("name", search.getData().getName());
        }
        if (search.getData() != null && search.getData().getAge() != null) {
            wrapper.eq("age", search.getData().getAge());
        }
        if (search.getData() != null && search.getData().getEmail() != null) {
            wrapper.eq("email", search.getData().getEmail());
        }

        return userMapper.selectPage(page, wrapper); //BaseMapper接口中的方法
    }

    // 模拟复杂分页查询：通过年龄分页查询
    public IPage<UserEntity> selectUserByAge(Page<UserEntity> page, Integer age) {
        return userMapper.selectUserByAge(page, age);
    }


    @Override
    public String login(@NotNull String username, @NotNull String password) {
//        1、从数据库查询账号是否存在 .select()查询指定字段
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>().select("username", "password").eq("username", username);
        UserEntity user = userMapper.selectOne(queryWrapper);
        System.out.println(user);
//        2、判断前端输入密码和数据库密码是否一致
//        user对象不为空 user的密码不为空
        if (!ObjectUtils.isEmpty(user) && !user.getPassWord().isEmpty()) {
            if (user.getPassWord().equals(password)) {
                return "token-" + username;
            }
        }
        return null;
    }


//////////////////////////CRUD操作////////////////////////////////////////////////////////////////////////


    @Override
    public Result insertUser(UserEntity user) {
        try {
            userMapper.insert(user);
            UserEntity select = userMapper.selectById(user.getId());
            if (select !=null){
                return Result.success(ResultCode.INSERT_SUCCESS, select, 1L);
            }else {
                return Result.failure(ResultCode.INSERT_FAILURE);
            }
        } catch (Exception e) {
            return Result.failure(ResultCode.INSERT_FAILURE_INDEX_UNIQUE_USERNAME);
        }
    }


    @Override
    public Result deleteUser(Integer id) {
        UserEntity select = userMapper.selectById(id);
        int delete = userMapper.deleteById(id);
        if (delete == 1) {
            return Result.success(ResultCode.DELETE_SUCCESS, select, 1L);
        } else {//没有数据时，select为null
            return Result.failure(ResultCode.DELETE_FAILURE_DATA_NOT_EXIST);
        }
    }


    @Override
    public Result updateUser(UserEntity user) {
        int update = userMapper.updateById(user);
        UserEntity select = userMapper.selectById(user.getId());
        if (update == 1) {
            return Result.success(ResultCode.UPDATE_SUCCESS, select, 1L);
        } else {
            return Result.failure(ResultCode.UPDATE_FAILURE, select, 0L);
        }
    }


    @Override
    public Result selectOne(Integer id) {
        UserEntity select = userMapper.selectById(id);
        if (select != null) {
            return Result.success(ResultCode.SELECT_SUCCESS, select, 1L);
        } else {
            return Result.success(ResultCode.SELECT_FAILURE, null, 0L);
        }

    }

    @Override
    public Result ChooseAll(SearchModel<UserEntity> search) {
        Page<UserEntity> page = new Page<>(search.getPageNum(), search.getPageSize());
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();

        if (search.getData() != null && search.getData().getName() != null) {
            wrapper.like("name", search.getData().getName());
        }
        if (search.getData() != null && search.getData().getAge() != null) {
            wrapper.eq("age", search.getData().getAge());
        }
        if (search.getData() != null && search.getData().getEmail() != null) {
            wrapper.eq("email", search.getData().getEmail());
        }

        userMapper.selectPage(page, wrapper);//BaseMapper接口中的方法
        return Result.success(ResultCode.SELECT_SUCCESS, page, page.getTotal());
    }


}

